package com.zhenyi.zhaozheng.admin.index;

import com.jfinal.aop.Clear;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.utils.AESUtils;
import com.utils.AuthUtils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;

public class AuthController extends ZZAdminController {

	@Clear
	public void index() {
		if (StrKit.notBlank(getPara("state"))) {
			String state = URLUtil.decode(getPara("state"));
			setAttr("URL", state);
		}
		// if (StrKit.notBlank(AuthUtils.getTokenUid(this))) {
		// redirect("");
		// }
		String key = RandomUtil.randomString(16);
		setAttr("key", key);
		setSessionAttr("key", key);
		render("/zz/admin/login.html");
	}

	@Clear
	public void login() {
		String account = getPara("account");
		String password = getPara("password");
		if (StrKit.isBlank(account)) {
			renderFailure(500, "请输入账号");
			return;
		}
		if (StrKit.isBlank(password)) {
			renderFailure(500, "请输入密码");
			return;
		}

		try {
			String key = getSessionAttr("key");
			password = AESUtils.decrypt(key, password);
			if (password == null) {
				renderFailure(500, "解密失败,请刷新重试");
				return;
			}

			if (!account.equals(PropKit.get("ZZ_ADMIN_ACCOUNT", "admin"))
					|| !password.equals(PropKit.get("ZZ_ADMIN_PASSWORD", "admin"))) {
				renderFailure(500, "账号/密码错误");
				return;
			}
			// DBMap map = new DBMap();
			// map.put("account", account);
			// map.put("password", password);
			// YqShopUser user = YqShopUser.dao.searchFirst(map);
			// if (user == null) {
			// renderFailure(500, "账号/密码错误");
			// return;
			// }
			// if (user.getStatus().equals(0)) {
			// renderFailure(500, "账号已被禁用");
			// return;
			// }
			// user.setLoginTime(new Date());
			// user.update();

			// String token = AuthUtils.login(String.valueOf(user.getId()), this);
			String token = AuthUtils.login(account, this);

			String redirectUrl = "/zz/admin/activity/list";
			renderSuccess(redirectUrl);
		} catch (Exception e) {
			e.printStackTrace();
			renderFailure("账号/密码错误");
			return;
		}
	}

	public void logout() {
		AuthUtils.logout(this);
		redirect("/zz/admin/auth");
	}
}
